#if defined(MIX_RTK)

#include "samples.h"

SHELL_CMD_FN(_rtk_sample_semaphore);

SHELL_REGISTER_CMD(
    register_sample_semaphore,
    SHELL_SETUP_CMD("sample-semaphore", "Kernel API example of: semaphore", _rtk_sample_semaphore, NULL), //
);

static rtk_thread_t s_thread1_handle;
static rtk_sem_t s_sem_handle;

static void _thread_1(void *arg)
{
    sh_t *sh_hdl = arg;
    rtk_thread_t *thread;
    const char *thread_name;

    thread = rtk_thread_get_self();
    thread_name = rtk_thread_get_name(thread);
    printf("this is '%s' running\r\n", thread_name);

    printf("%s: waiting the samphore ..\r\n", thread_name);
    if (rtk_sem_take(&s_sem_handle, RTK_WAIT_FOREVER) != RTK_OK)
    {
        SYS_LOG_ERR("takeing semaphore fail!");
        rtk_thread_delete(NULL);
        return;
    }

    printf("%s: take samphore success, waiting to take again ...\r\n", thread_name);
    if (rtk_sem_take(&s_sem_handle, RTK_WAIT_FOREVER) != RTK_OK)
    {
        SYS_LOG_ERR("takeing semaphore fail!");
        rtk_thread_delete(NULL);
        return;
    }

    printf("%s: take samphore success\r\n", thread_name);

    printf("%s: run complete\r\n", thread_name);
    rtk_thread_delete(NULL);
}

SHELL_CMD_FN(_rtk_sample_semaphore)
{
    tag();

    rtk_thread_t *thread;
    const char *thread_name;

    thread = rtk_thread_get_self();
    thread_name = rtk_thread_get_name(thread);

    do
    {
        printf("create a semaphore object\r\n");
        if (rtk_sem_create(&s_sem_handle, "sem1", 0, 1, RTK_SEM_TYPE_FIFO) != RTK_OK)
        {
            break;
        }

        printf("you can release semaphore any time\r\n");
        rtk_sem_release(&s_sem_handle);

        printf("create and wait thread-1 to run ...\r\n");
        rtk_thread_create(&s_thread1_handle,
                         "thread-1",
                         _thread_1,
                         sh_hdl,
                         0x400,
                         1,
                         0);
        rtk_thread_sleep(100);

        printf("this is '%s' running\r\n", rtk_thread_get_name(thread));

        printf("release semaphore again and wait ...\r\n");
        rtk_sem_release(&s_sem_handle);
        rtk_thread_sleep(100);

        printf("%s: run complete\r\n", thread_name);

        printf("objects can be deleted when they are no longer used\r\n");
        rtk_sem_delete(&s_sem_handle);

        return 0;

    } while (0);

    rtk_sem_delete(&s_sem_handle);

    printf("operate fail!\r\n");
    return -1;
}

#endif /* #if defined(MIX_RTK) */
